
const express = require('express');
const cors = require('cors');
const fs = require('fs');
const path = require('path');

const app = express();
const PORT = 3001;
const DB_PATH = path.join(__dirname, 'db.json');

// Middleware
app.use(cors());
app.use(express.json());

// Helper function to read the database
const readDB = () => {
  const dbRaw = fs.readFileSync(DB_PATH);
  return JSON.parse(dbRaw);
};

// Helper function to write to the database
const writeDB = (data) => {
  fs.writeFileSync(DB_PATH, JSON.stringify(data, null, 2));
};

// --- API Endpoints ---

// Get all products and categories
app.get('/api/products', (req, res) => {
  try {
    const db = readDB();
    res.json({ categories: db.categories, products: db.products });
  } catch (error) {
    res.status(500).json({ message: 'Error reading database', error });
  }
});

// Submit a new order
app.post('/api/orders', (req, res) => {
  console.log(`[${new Date().toLocaleString()}] POST /api/orders`, req.body);
  try {
    const db = readDB();
    const newOrder = {
      orderId: `ORD${Date.now()}`,
      timestamp: new Date().toISOString(),
      status: '备货中',
      statusTheme: 'warning',
      ...req.body, // req.body contains items, roomId
      totalAmount: parseFloat(req.body.totalAmount || 0)
    };
    db.orders.unshift(newOrder);
    writeDB(db);
    res.status(201).json({ success: true, orderId: newOrder.orderId });
  } catch (error) {
    res.status(500).json({ message: 'Error processing order', error });
  }
});

// Get orders for a specific room
app.get('/api/orders/room/:id', (req, res) => {
  try {
    const db = readDB();
    const roomId = req.params.id;
    const roomOrders = db.orders.filter(order => order.roomId === roomId);
    res.json(roomOrders);
  } catch (error) {
    res.status(500).json({ message: 'Error reading database', error });
  }
});

// Get all orders (for admin)
app.get('/api/orders', (req, res) => {
  console.log(`[${new Date().toLocaleString()}] GET /api/orders`);
  try {
    const db = readDB();
    // Sort by timestamp descending
    const sortedOrders = db.orders.sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp));
    res.json(sortedOrders);
  } catch (error) {
    res.status(500).json({ message: 'Error reading database', error });
  }
});

// Update an order's status
app.put('/api/orders/:id/status', (req, res) => {
  console.log(`[${new Date().toLocaleString()}] PUT /api/orders/${req.params.id}/status`, req.body);
  try {
    const db = readDB();
    const orderId = req.params.id;
    const { status } = req.body; // e.g., { status: '配送中' }

    const orderIndex = db.orders.findIndex(o => o.orderId === orderId);
    if (orderIndex === -1) {
      return res.status(404).json({ message: 'Order not found' });
    }

    // Define themes for statuses
    const statusThemes = {
      '备货中': 'warning',
      '配送中': 'primary',
      '已完成': 'success',
      '已取消': 'danger',
    };

    db.orders[orderIndex].status = status;
    db.orders[orderIndex].statusTheme = statusThemes[status] || 'default';

    writeDB(db);
    res.json(db.orders[orderIndex]);
  } catch (error) {
    res.status(500).json({ message: 'Error updating order status', error });
  }
});

// --- Product Management Endpoints ---

// Add a new product
app.post('/api/products', (req, res) => {
  try {
    const db = readDB();
    // Save price as a float in yuan
    const newProduct = { id: `p${Date.now()}`, ...req.body, price: parseFloat(req.body.price || 0) };
    db.products.push(newProduct);
    writeDB(db);
    res.status(201).json(newProduct);
  } catch (error) {
    res.status(500).json({ message: 'Error adding product', error });
  }
});

// Update an existing product
app.put('/api/products/:id', (req, res) => {
  try {
    const db = readDB();
    const productId = req.params.id;
    const productIndex = db.products.findIndex(p => p.id === productId);
    if (productIndex === -1) {
      return res.status(404).json({ message: 'Product not found' });
    }
    // Save price as a float in yuan
    const updatedProduct = { ...db.products[productIndex], ...req.body, price: parseFloat(req.body.price || 0) };
    db.products[productIndex] = updatedProduct;
    writeDB(db);
    res.json(updatedProduct);
  } catch (error) {
    res.status(500).json({ message: 'Error updating product', error });
  }
});

// Delete a product
app.delete('/api/products/:id', (req, res) => {
  try {
    const db = readDB();
    const productId = req.params.id;
    const newProducts = db.products.filter(p => p.id !== productId);
    if (db.products.length === newProducts.length) {
      return res.status(404).json({ message: 'Product not found' });
    }
    db.products = newProducts;
    writeDB(db);
    res.status(200).json({ message: 'Product deleted successfully' });
  } catch (error) {
    res.status(500).json({ message: 'Error deleting product', error });
  }
});

// Serve the admin page
app.get('/admin', (req, res) => {
  res.sendFile(path.join(__dirname, 'public', 'admin.html'));
});

// Start the server
app.listen(PORT, () => {
  console.log(`Backend server is running on http://localhost:${PORT}`);
});
